﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DispatchAssist.Model;
using DispatchAssist.BusinessLogical.DAL;
using CarolLib;
using DispatchAssist.BusinessLogical.Model;
using System.Collections;
//using CarolLib.Core;

namespace DispatchAssist.BusinessLogical.BLL
{
    public class ClientInfoCacheHelper
    {

        #region members
        private static log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private static IDataProvider _provider = new SqlDataProvider();

        private static List<string> DelegateSeatIDs;

        private static object locker = new object();

        public static ClientMessageInfo CacheData { set; get; }
        #endregion 

        /// <summary>
        /// 
        /// </summary>
        public static void GetNewCacheData()
        {
            try
            {
                if (CacheData == null)
                {
                    CacheData = new ClientMessageInfo();
                }

                lock (locker)
                {
                    List<NormalAlertInfo> alertList = GetNormalAlertList();

                    List<SMSAlertAllInfo> smsList = GetSMSAlertList();

                    List<SeatRelation> delegateSeatList = GetSeatRelation();

                    CacheData.NormalAlertList = alertList == null ? new List<NormalAlertInfo>() : alertList;

                    CacheData.SMSAlertList = smsList == null ? new List<SMSAlertAllInfo>() : smsList;

                    CacheData.RelationSeats = delegateSeatList == null ? new List<SeatRelation>() : delegateSeatList;
                }
            }
            catch (Exception e)
            {
                Logger.Error("get cache data from DB error", e);
            }

        }

        public static ClientMessageInfo GetClientAlertListBySeatIDs(string SelfSeatID, string[] RelationSeatIDs)
        {
            if (CacheData == null || (CacheData.NormalAlertList == null && CacheData.SMSAlertList == null))
            {
                GetNewCacheData();
            }

            if (RelationSeatIDs == null)
            {
                RelationSeatIDs = new string[0];
            }
            //获取子代理席位
            lock (locker)
            {
                DelegateSeatIDs = new List<string>();

                try
                {
                    foreach (string delegateSeat in RelationSeatIDs)
                    {
                        GetChildDelegateSeats(new Guid(delegateSeat));
                    }
                }
                catch (Exception e)
                {
                    Logger.Error("error in get child delegate seat",e);
                }
            }

            //根据主席位和代理席位获取客户端所需数据
            ClientMessageInfo result = new ClientMessageInfo();

            try
            {
                result.NormalAlertList = CacheData.NormalAlertList.Where(f => f.SeatID.ToString().ToLower() == SelfSeatID.ToLower() || DelegateSeatIDs.Contains(f.SeatID.ToString())).ToList();
                result.SMSAlertList = CacheData.SMSAlertList.Where(f => f.SeatID.ToString().ToLower() == SelfSeatID.ToLower() || DelegateSeatIDs.Contains(f.SeatID.ToString())).ToList();
                result.SeatLoginList = CommonCacheData.CacheLonginSeatInfo.GetSeatLoginInfoList(SelfSeatID);
                result.RelationSeats = CacheData.RelationSeats;//.Where(f => f.SelfSeatID == new Guid(SelfSeatID)).ToList();
            }
            catch (Exception e)
            {
                Logger.Error("Get Data from Cache  error", e);
            }

            return result;
        }


        public static ClientMessageInfo GetClientAlertListBySeat(string seatID)
        {

            if (CacheData == null || (CacheData.NormalAlertList == null && CacheData.SMSAlertList == null))
            {
                GetNewCacheData();
            }

            ClientMessageInfo result = new ClientMessageInfo();

            try
            {
                result.NormalAlertList = CacheData.NormalAlertList.Where(f => f.SeatID.ToString().ToLower() == seatID.ToLower()).ToList();
                result.SMSAlertList = CacheData.SMSAlertList.Where(f => f.SeatID.ToString().ToLower() == seatID.ToLower()).ToList();
                result.RelationSeats = CacheData.RelationSeats.Where(f => f.SelfSeatID == new Guid(seatID)).ToList();
                result.SeatLoginList = CommonCacheData.CacheLonginSeatInfo.GetSeatLoginInfoList(seatID);
            }
            catch (Exception e)
            {
                Logger.Error("Get Data from Cache  error", e);
            }

            return result;

        }

        /// <summary>
        /// 返回json格式
        /// </summary>
        /// <param name="seatID"></param>
        /// <returns></returns>
        public static string GetJsonClientAlertListBySeat(string seatID)
        {
            ClientMessageInfo result = GetClientAlertListBySeat(seatID);

            string jsonResult = "";
            try
            {
                jsonResult = JsonSerializeHelper.DataContractJsonSerializeByJNet(result);
            }
            catch (Exception e)
            {
                Logger.Error("error in Serialize object to json", e);
            }

            return jsonResult;
        }

        public static string GetJsonClientAlertListBySeat(string SelfSeatID, string[] RelationSeatIDs)
        {
            ClientMessageInfo result = GetClientAlertListBySeatIDs(SelfSeatID, RelationSeatIDs);

            string jsonResult = "";
            try
            {
                jsonResult = JsonSerializeHelper.DataContractJsonSerializeByJNet(result);
            }
            catch (Exception e)
            {
                Logger.Error("error in Serialize object to json", e);
            }

            return jsonResult;
        }

        public static string ReturnJsonStr(object obj)
        {
            string jsonResult = "";
            try
            {
                jsonResult = JsonSerializeHelper.DataContractJsonSerializeByJNet(obj);
            }
            catch (Exception e)
            {
                Logger.Error("error in Serialize object to json", e);
            }
            return jsonResult;
        }


        #region private methods
        /// <summary>
        /// 拆分普通预警
        /// </summary>
        /// <returns></returns>
        private static List<NormalAlertInfo> GetNormalAlertList()
        {
            List<AlertAllInfo> alertList = _provider.GetRecentClientAlertInfo();

            List<NormalAlertInfo> result = new List<NormalAlertInfo>();

            //  Guid[] ids = alertList.Distinct(new Comparint()).ToDictionary<NormalAlertInfo, Guid>(f => f.AlertID).Keys.ToArray();

            //   List<AlertAllInfo> infoList = _provider.GetAlertInfoByIDs(ids);

            foreach (AlertAllInfo info in alertList)
            {
                //List<AlertAllInfo> aainfo = infoList.Where(f => f.AlertID == info.AlertID).ToList<AlertAllInfo>();

                //List<NormalAlertInfo> newList = SplitNormalAlertModel(info,aainfo[0]);

                List<NormalAlertInfo> newList = SplitNormalAlertModel(info.ClientModelInfo, info);

                result.AddRange(newList);
            }

            return result;
        }

        /// <summary>
        /// 拆分短信预警
        /// </summary>
        /// <returns></returns>
        private static List<SMSAlertAllInfo> GetSMSAlertList()
        {
            List<SMSAlertAllInfo> smsList = _provider.GetRecentClientSMSAlertInfo();

            List<SMSAlertAllInfo> result = new List<SMSAlertAllInfo>();

            foreach (SMSAlertAllInfo info in smsList)
            {

                List<SMSAlertAllInfo> newList = SplitSMSAlertModel(info);

                result.AddRange(newList);
            }

            return result;
        }

        public static List<NormalAlertInfo> SplitNormalAlertModel(NormalAlertInfo model, AlertAllInfo source)
        {
            List<int> actions = model.SplitActionFlags();

            List<NormalAlertInfo> result = new List<NormalAlertInfo>();
            foreach (int action in actions)
            {
                try
                {
                    string targetType = "";

                    if (action == (int)Enums.AlertActionFlag.ManualSendAcrarsAlert || action == (int)(Enums.AlertActionFlag.AutoSendAcarsAlert | Enums.AlertActionFlag.ConfirmAcars))
                    {
                        targetType = CommonCacheData.CacheACARDevice.GetACARSDeviceTypeByPara(model.TailNo);
                    }

                    string template = CommonCacheData.CacheTemplate.GetTemplateContentByPara(action, targetType);

                    string message;

                    try
                    {
                        message = MessageBodyFactory.GetMessageBody<AlertAllInfo>(source, template);
                    }
                    catch
                    {
                        message = "";
                    }

                    NormalAlertInfo normalAlert = model.CopyModel();
                    normalAlert.AlertActionFlag = action;
                    normalAlert.MessageBody = message;

                    result.Add(normalAlert);
                }
                catch (Exception e)
                {
                    Logger.Error("error in SplitNormalAlertModel action:", e);
                    continue;
                }
            }

            return result;
        }

        public static List<SMSAlertAllInfo> SplitSMSAlertModel(SMSAlertAllInfo model)
        {
            List<int> actions = model.SplitActionFlags();

            List<SMSAlertAllInfo> result = new List<SMSAlertAllInfo>();
            foreach (int action in actions)
            {


                string template = CommonCacheData.CacheTemplate.GetTemplateContentByPara(action, null);

                if (string.IsNullOrEmpty(template))
                {
                    Logger.Error("no template info ,action:" + action.ToString());
                    continue;
                }

                try
                {
                    string message = MessageBodyFactory.GetMessageBody<SMSAlertAllInfo>(model, template);

                    SMSAlertAllInfo info = model.CopyModel();
                    info.AlertActionFlag = action;
                    info.MessageBody = message;

                    result.Add(info);
                }
                catch (Exception e)
                {
                    Logger.Error(e);

                    continue;
                }
            }

            return result;
        }

        private static List<SeatRelation> GetSeatRelation()
        {
            List<SeatRelation> result;
            try
            {
                result = _provider.GetSeatRelation();
            }
            catch (Exception e)
            {
                Logger.Error(e);
                result = null;
            }

            return result;
        }

        private static void GetChildDelegateSeats(Guid ParentSeat)
        {
            var items = CacheData.RelationSeats.Where(f=>(f.SelfSeatID==ParentSeat)&&(f.ConfirmStatus==3));

            if (items == null || items.Count() == 0)
            {
                if (!DelegateSeatIDs.Contains(ParentSeat.ToString()))
                {
                    DelegateSeatIDs.Add(ParentSeat.ToString());
                }
            }
            else
            {
                ArrayList list = new ArrayList();
                foreach (var item in items)
                {
                    if (!DelegateSeatIDs.Contains(item.SelfSeatID.ToString()))
                    {
                        DelegateSeatIDs.Add(item.SelfSeatID.ToString());
                    }
                    GetChildDelegateSeats(item.DelegateSeatID);
                }
            }
        }

        #endregion
    }
}
